// 简化版聊天应用
let sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
let isConnected = false;
let websocket = null;

// 初始化函数
function initApp() {
    console.log('初始化聊天应用...');
    
    // 获取DOM元素
    const sendButton = document.getElementById('sendButton');
    const messageInput = document.getElementById('messageInput');
    const clearButton = document.getElementById('clearButton');
    const connectionStatus = document.getElementById('connectionStatus');
    const currentTimeElement = document.getElementById('currentTime');
    const exampleButtons = document.querySelectorAll('.example-btn');
    
    // 检查元素是否存在
    if (!sendButton || !messageInput) {
        console.error('关键DOM元素未找到');
        return;
    }
    
    console.log('DOM元素获取成功');
    
    // 绑定发送按钮事件
    sendButton.addEventListener('click', function() {
        console.log('发送按钮被点击');
        sendMessage();
    });
    
    // 绑定回车键事件
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            console.log('回车键被按下');
            e.preventDefault();
            sendMessage();
        }
    });
    
    // 绑定清除按钮事件
    if (clearButton) {
        clearButton.addEventListener('click', function() {
            console.log('清除按钮被点击');
            clearHistory();
        });
    }
    
    // 绑定示例按钮事件
    exampleButtons.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const message = btn.getAttribute('data-message');
            console.log('示例按钮被点击:', message);
            messageInput.value = message;
            sendMessage();
        });
    });
    
    // 更新连接状态
    if (connectionStatus) {
        connectionStatus.textContent = '已连接 (HTTP)';
        connectionStatus.className = 'connection-status';
    }
    
    // 更新当前时间
    updateCurrentTime();
    setInterval(updateCurrentTime, 60000);
    
    // 尝试连接WebSocket
    connectWebSocket();
    
    console.log('聊天应用初始化完成');
}

// 发送消息函数
async function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    
    const message = messageInput.value.trim();
    if (!message) {
        console.log('消息为空，跳过发送');
        return;
    }
    
    console.log('发送消息:', message);
    
    // 添加用户消息到界面
    addMessage(message, 'user');
    messageInput.value = '';
    
    // 禁用发送按钮
    sendButton.disabled = true;
    sendButton.textContent = '发送中...';
    
    // 显示输入指示器
    showTypingIndicator();
    
    try {
        // 优先使用WebSocket
        if (isConnected && websocket && websocket.readyState === WebSocket.OPEN) {
            console.log('使用WebSocket发送消息');
            websocket.send(JSON.stringify({
                type: 'message',
                message: message
            }));
        } else {
            console.log('使用HTTP API发送消息');
            await sendMessageHTTP(message);
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        removeTypingIndicator();
        addMessage('抱歉，发送消息时出现了错误：' + error.message, 'assistant');
    } finally {
        // 重新启用发送按钮
        sendButton.disabled = false;
        sendButton.textContent = '发送';
    }
}

// HTTP发送消息
async function sendMessageHTTP(message) {
    console.log('发送HTTP请求...');
    
    const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            sessionId: sessionId,
            message: message
        })
    });
    
    console.log('收到HTTP响应，状态:', response.status);
    
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    console.log('响应数据:', data);
    
    removeTypingIndicator();
    addMessage(data.content, 'assistant', data.timestamp);
}

// 添加消息到界面
function addMessage(content, role, timestamp) {
    const chatMessages = document.getElementById('chatMessages');
    if (!chatMessages) {
        console.error('chatMessages元素未找到');
        return;
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.innerHTML = formatMessage(content);
    
    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';
    timeDiv.textContent = timestamp || getCurrentTime();
    
    messageDiv.appendChild(contentDiv);
    messageDiv.appendChild(timeDiv);
    
    chatMessages.appendChild(messageDiv);
    scrollToBottom();
    
    console.log('添加消息:', role, content.substring(0, 50) + '...');
}

// 格式化消息
function formatMessage(content) {
    return content
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>');
}

// 显示输入指示器
function showTypingIndicator() {
    removeTypingIndicator();
    
    const chatMessages = document.getElementById('chatMessages');
    const typingDiv = document.createElement('div');
    typingDiv.className = 'message assistant';
    typingDiv.id = 'typing-indicator';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'typing-indicator';
    contentDiv.innerHTML = `
        <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
        </div>
    `;
    
    typingDiv.appendChild(contentDiv);
    chatMessages.appendChild(typingDiv);
    scrollToBottom();
}

// 移除输入指示器
function removeTypingIndicator() {
    const typingIndicator = document.getElementById('typing-indicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
}

// 滚动到底部
function scrollToBottom() {
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 获取当前时间
function getCurrentTime() {
    return new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 更新当前时间
function updateCurrentTime() {
    const currentTimeElement = document.getElementById('currentTime');
    if (currentTimeElement) {
        currentTimeElement.textContent = getCurrentTime();
    }
}

// 清除历史
async function clearHistory() {
    if (!confirm('确定要清除所有聊天记录吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/chat/${sessionId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            const chatMessages = document.getElementById('chatMessages');
            const messages = chatMessages.querySelectorAll('.message');
            messages.forEach((msg, index) => {
                if (index > 0) { // 保留第一条欢迎消息
                    msg.remove();
                }
            });
            console.log('历史记录已清除');
        } else {
            alert('清除历史记录失败');
        }
    } catch (error) {
        console.error('清除历史记录失败:', error);
        alert('清除历史记录失败');
    }
}

// WebSocket连接
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/api/ws/${sessionId}`;
    
    try {
        websocket = new WebSocket(wsUrl);
        
        websocket.onopen = function() {
            console.log('WebSocket连接已建立');
            isConnected = true;
            updateConnectionStatus('已连接 (WebSocket)');
        };
        
        websocket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            handleWebSocketMessage(data);
        };
        
        websocket.onclose = function() {
            console.log('WebSocket连接已关闭');
            isConnected = false;
            updateConnectionStatus('已连接 (HTTP)');
            
            // 尝试重连
            setTimeout(connectWebSocket, 5000);
        };
        
        websocket.onerror = function(error) {
            console.error('WebSocket错误:', error);
            isConnected = false;
            updateConnectionStatus('已连接 (HTTP)');
        };
    } catch (error) {
        console.error('WebSocket连接失败:', error);
        isConnected = false;
        updateConnectionStatus('已连接 (HTTP)');
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    if (data.type === 'stream') {
        appendToLastMessage(data.content);
    } else if (data.type === 'end') {
        removeTypingIndicator();
    } else if (data.type === 'error') {
        removeTypingIndicator();
        addMessage('抱歉，处理您的请求时出现了错误。', 'assistant');
    }
}

// 追加到最后一条消息
function appendToLastMessage(content) {
    const chatMessages = document.getElementById('chatMessages');
    const messages = chatMessages.querySelectorAll('.message.assistant');
    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        const contentDiv = lastMessage.querySelector('.message-content');
        if (contentDiv) {
            contentDiv.innerHTML += formatMessage(content);
            scrollToBottom();
        }
    }
}

// 更新连接状态
function updateConnectionStatus(status) {
    const connectionStatus = document.getElementById('connectionStatus');
    if (connectionStatus) {
        connectionStatus.textContent = status;
        connectionStatus.className = 'connection-status';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化...');
    
    // 添加全局错误处理
    window.addEventListener('error', function(e) {
        console.error('全局错误:', e.error);
    });
    
    // 检查必要的API支持
    if (!window.fetch) {
        alert('您的浏览器不支持fetch API，请使用现代浏览器');
        return;
    }
    
    try {
        initApp();
    } catch (error) {
        console.error('初始化失败:', error);
        alert('初始化失败: ' + error.message);
    }
});

console.log('app-simple.js 加载完成');
